def list_b_pinyin_combinations():
    combinations = {}
    try:
        with open('input/text_data.txt', 'r', encoding='utf-8') as f:
            for line in f:
                split_result = line.split();
                py = split_result[0]
                ch = split_result[1]
                combinations[py] = ch
    except FileNotFoundError:
        print("文件未找到，请检查文件路径。")
    return combinations

import base64
import csv
import json
import random
import requests
import os
import uuid

def gen_audio(text, output_file):
    appid = "8694880241"
    access_token= "phMLsOxGntkuYUGmbQ_x4IGPdjqU8uX7"
    cluster = "volcano_tts"

    voice_type = "BV002_streaming"
    host = "openspeech.bytedance.com"
    api_url = f"https://{host}/api/v1/tts"

    header = {"Authorization": f"Bearer;{access_token}"}

    request_json = {
        "app": {
            "appid": appid,
            "token": access_token,
            "cluster": cluster
        },
        "user": {
            "uid": "2103587455"
        },
        "audio": {
            "voice_type": voice_type,
            "encoding": "mp3",
            "speed_ratio": 1.0,
            "volume_ratio": 1.0,
            "pitch_ratio": 1.0,
        },
        "request": {
            "reqid": str(uuid.uuid4()),
            "text": text,
            "text_type": "plain",
            "operation": "query",
            "with_frontend": 1,
            "frontend_type": "unitTson"
        }
    }
    resp = requests.post(api_url, json.dumps(request_json), headers=header)
    print(f"resp body: \n{resp.json()}")
    if "data" in resp.json():
        data = resp.json()["data"]
        file_to_save = open(output_file, "wb")
        file_to_save.write(base64.b64decode(data))

def generate_audios(combinations, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    for pinyin in combinations.keys():
        output_file = os.path.join(output_dir, f"{pinyin}.mp3")
        if not os.path.exists(output_file):
            gen_audio(pinyin, output_file)

def generate_anki_txt(combinations, filename):
    with open(filename, 'w', encoding='utf-8') as txtfile:
        # 生成形式一：拼音 -> 汉字
        for pinyin, character in combinations.items():
            txtfile.write(f'<font size="10">{pinyin}</font>\t<font size="10">{character}</font><br>[sound:{pinyin}.mp3]\n')
        
        # 生成形式二：汉字 + 相似拼音 -> 正确拼音
        pinyin_list = list(combinations.keys())
        for pinyin, character in combinations.items():
            # 随机选择3个错误拼音
            wrong_pinyins = random.sample([p for p in pinyin_list if p != pinyin], 3)
            options = wrong_pinyins + [pinyin]
            random.shuffle(options)
            question = f'[sound:{pinyin}.mp3]<br>' + "<br>".join([f"<font size=10>{i+1} {opt}</font>" for i, opt in enumerate(options)])
            txtfile.write(f'{question}\t<font size=10>{pinyin}</font>\n')

if __name__ == '__main__':
    combinations = list_b_pinyin_combinations()
    
    # 打印拼音组合
    for pinyin, character in combinations.items():
        print(f"{pinyin} - {character}")
    
    # 清空并创建output目录
    output_dir = 'output'
    if os.path.exists(output_dir):
        print("\noutput文件夹已存在，包含以下内容：")
        for root, dirs, files in os.walk(output_dir):
            for name in files:
                print(f"文件: {os.path.join(root, name)}")
            for name in dirs:
                print(f"目录: {os.path.join(root, name)}")
        
        confirm = input("\n是否清空output文件夹？(y/n): ")
        if confirm.lower() == 'y':
            print("\n正在清空output文件夹...")
            for root, dirs, files in os.walk(output_dir, topdown=False):
                for name in files:
                    try:
                        os.remove(os.path.join(root, name))
                        print(f"已删除文件: {os.path.join(root, name)}")
                    except:
                        print(f"无法删除文件: {os.path.join(root, name)}")
                for name in dirs:
                    try:
                        os.rmdir(os.path.join(root, name))
                        print(f"已删除目录: {os.path.join(root, name)}")
                    except:
                        print(f"无法删除目录: {os.path.join(root, name)}")
        else:
            print("\n跳过清空output文件夹")
    
    try:
        os.makedirs(output_dir, exist_ok=True)
        print(f"\n已创建output目录: {output_dir}")
    except:
        print("\n无法创建output目录")

    # 生成音频文件
    audio_output_dir = os.path.join(output_dir, 'audio')
    generate_audios(combinations, audio_output_dir)
    print(f"\n音频文件已生成到目录：{audio_output_dir}")

    # 生成Anki导入文件
    output_file = os.path.join(output_dir, 'b_pinyin_anki_import.txt')
    generate_anki_txt(combinations, output_file)
    print(f"\nAnki导入文件已生成：{output_file}")

    # 打印TXT文件内容
    print("\nTXT文件内容：")
    with open(output_file, 'r', encoding='utf-8') as f:
        print(f.read())
